<template>
  <div class="article">
    <form class="form-wrap">
      <div class="header">
        <div ref="editorTop" class="toolbar"></div>
      </div>
      <div ref="editorBody" class="textContent">
        <!--可使用 min-height 实现编辑区域自动增加高度-->
      </div>
      <div class="h4">
        <input class="outline-title" type="text" v-model="formParams.title" maxlength="30" placeholder="请输入文章标题（5到30个字）" />
      </div>
      <div class="line-divider"></div>
      <div class="form-container">
        <el-row>
          <el-col :span="6"> <i style="color:red">*</i> 展示封面 </el-col>
          <el-col :span="18">
            <el-radio-group v-model="formParams.radioImg" @change="radioImgChange">
              <el-radio label="1">单图</el-radio>
              <el-radio label="2">三图</el-radio>
              <el-radio label="3">无封面</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
        <el-row style="margin-top:28px" v-if="formParams.radioImg == '1'">
          <el-col :span="18" :offset="6">
            <div class="article-cover-add" @click="selectImgVisible = true">
              <i class="el-icon-plus" v-if="!formParams.bannerImgUrl"></i>
              <div class="template" v-else @mouseover="oneBannerMouseover" @mouseleave="oneBannerMouseleave">
                <img class="article-cover-img" :src="formParams.bannerImgUrl" alt="" />
                <i class="article-cover-delete el-icon-circle-close" v-if="oneBannerSelectFlag" @click.stop="deleteSelectOneImg"></i>
              </div>
            </div>
            <span class="show-dialog-btn" @click="previewTitle(1)">预览</span>
            <p class="article-cover-tip">优质的封面有利于推荐，格式支持JPEG、PNG</p>
          </el-col>
        </el-row>
        <el-row style="margin-top:28px" v-if="formParams.radioImg == '2'">
          <el-col :span="18" :offset="6">
            <div class="article-cover-add" v-for="(item, index) in 3" :key="item" @click="selectThreeImg(index)">
              <i class="el-icon-plus" v-if="formParams.bannerImgList.length < item"></i>
              <div class="template" v-else @mouseover="bannerMouseover(item)" @mouseleave="bannerMouseleave(item)">
                <img class="article-cover-img" :src="formParams.bannerImgList[index]" alt="" />
                <i class="article-cover-delete el-icon-circle-close" v-if="moreSelectFlag(item)" @click.stop="deleteSelectMoreImg(index)"></i>
              </div>
            </div>
            <span class="show-dialog-btn" @click="previewTitle(3)">预览</span>
            <p class="article-cover-tip">优质的封面有利于推荐，格式支持JPEG、PNG</p>
          </el-col>
        </el-row>
        <el-row style="margin-top:48px">
          <el-col :span="6"> <span style="margin-left:10px">发文特权</span> </el-col>
          <el-col :span="18">
            <el-checkbox v-model="formParams.upLinkCheck">扩展链接</el-checkbox>
            <div class="form-input" v-if="formParams.upLinkCheck">
              <input class="my-input" v-model="formParams.link" placeholder="请输入链接地址" />
            </div>
          </el-col>
        </el-row>
        <el-row style="margin-top:48px">
          <el-col :span="6"> <i style="color:red">*</i> 投放广告 </el-col>
          <el-col :span="18">
            <el-radio v-model="formParams.radioAd" label="1">投放广告赚收益</el-radio>
            <el-radio v-model="formParams.radioAd" label="2">不投放广告</el-radio>
          </el-col>
        </el-row>
      </div>
    </form>
    <div class="bottom-fix">
      <div class="publish-footer-content">
        <p class="footer-tip">正文字数：{{ editorContentSize }}</p>
        <div class="go-back">
          <router-link to="/"><el-button size="small" icon="el-icon-back" circle></el-button></router-link>
        </div>
        <div class="footer-btn">
          <el-button size="small" @click="previewContent">预览</el-button>
          <el-button size="small" :disabled="postId != ''" @click="selectPushTime">定时发布</el-button>
          <el-button size="small" type="danger" :loading="btnLoading" @click="submitPublish(1)">
            {{ postId ? '更新' : '发布' }}
          </el-button>
        </div>
      </div>
    </div>
    <!-- 选择图片 -->
    <select-img
      :selectImgVisible="selectImgVisible"
      :bannerNum="bannerNum"
      @closeVisible="selectImgVisible = false"
      @select-recommend-img="selectRecommendImg"
    />
    <!-- 标题预览 -->
    <drawer-title :drawerTitleVisible="drawerTitleVisible" :title="formParams.title" :imgList="imgList" @beforeClose="drawerTitleVisible = false" />
    <!-- 内容预览 -->
    <transition name="fade">
      <drawer-content
        :drawerContentVisible="drawerContentVisible"
        :title="formParams.title"
        :previewContent="editorTxt"
        @closePrview="drawerContentVisible = false"
        v-if="drawerContentVisible"
      />
    </transition>
    <!-- 定时发送时间选择 -->
    <select-time :selectTimeVisible="selectTimeVisible" :loading="timeLoading" @handleClose="selectTimeVisible = false" @submit="timingPublish" />
  </div>
</template>

<script>
import wangEditor from 'wangeditor';
import SelectImg from '../select-img';
import DrawerTitle from '../drawer-title';
import DrawerContent from '../drawer-content';
import SelectTime from '../select-time';
import { createPost, createSchedulePost, queryPostDetail, updatePost } from '../api';
import { mapGetters } from 'vuex';

export default {
  components: { SelectImg, DrawerTitle, DrawerContent, SelectTime },
  data() {
    return {
      editor: '', // 富文本编辑器
      editorContentChange: 0,
      editorContentSize: 0,
      formParams: {
        title: '',
        radioImg: '1',
        bannerImgUrl: '', // 一张封面
        bannerImgList: [], // 三张封面
        upLinkCheck: false,
        link: '',
        radioAd: '1'
      },
      overstepIdx: '', // 三张图替换标识
      selectImgVisible: false,
      oneBannerSelectFlag: false, // 显示单张图片删除标识
      bannerNum: 1, // 1张 3张
      moreOneSelectFlag: false, // 显示三张图片删除标识
      moreTwoSelectFlag: false,
      moreThreeSelectFlag: false,
      drawerTitleVisible: false, // 标题预览
      imgList: [], // 预览图片
      drawerContentVisible: false, // 内容预览
      editorTxt: '', // 预览内容
      selectTimeVisible: false, // 定时发送时间选择
      timeLoading: false,
      btnLoading: false // 提交节流
    };
  },
  computed: {
    ...mapGetters(['userId']),
    postId() {
      return this.$route.query.postId || '';
    }
  },
  watch: {
    editorContentChange() {
      this.editorContentSize = this.editor.txt.text().length;
    }
  },
  mounted() {
    this.editor = new wangEditor(this.$refs.editorTop, this.$refs.editorBody);
    this.editor.config.onchange = html => {
      // html 即变化之后的内容
      this.editorContentChange++;
    };
    this.editor.config.zIndex = 0;
    // 自定义菜单配置
    this.editor.config.menus = [
      'head', // 标题
      'bold', // 粗体
      'fontSize', // 字号
      'fontName', // 字体
      'italic', // 斜体
      'underline', // 下划线
      'lineHeight', // 行高
      'strikeThrough', // 删除线
      'foreColor', // 文字颜色
      'backColor', // 背景颜色
      'link', // 插入链接
      'list', // 列表
      'justify', // 对齐方式
      'table', // 表格
      'code', // 代码
      'quote', // 引用
      'emoticon', // 表情
      'image' // 图片
    ];
    // 挂载highlight插件
    this.editor.highlight = window.hljs;
    this.editor.create();
    if (this.postId) {
      queryPostDetail({ postId: this.postId }).then(res => {
        if (res.success) {
          this.dealData(res.data);
        }
      });
    }
  },
  methods: {
    dealData(data) {
      this.formParams.title = data.title;
      switch (data.coverSize) {
        case 0:
          this.formParams.radioImg = '3';
          break;
        case 1:
          this.formParams.radioImg = '1';
          this.formParams.bannerImgUrl = data.coverImg[0];
          break;
        case 3:
          this.formParams.radioImg = '2';
          this.formParams.bannerImgList = data.coverImg;
          break;
      }
      this.editor.txt.html(data.content); // 重新设置编辑器内容
    },
    timingPublish(data) {
      this.timeLoading = true;
      this.submitPublish(2, data);
    },
    selectPushTime() {
      if (this.checkParams()) {
        this.selectTimeVisible = true;
      }
    },
    previewContent() {
      if (this.checkTitle()) {
        if (!this.editor.txt.html()) {
          this.$message.error('请输入文章内容');
          return false;
        }
        this.editorTxt = this.editor.txt.html();
        this.drawerContentVisible = true;
      }
    },
    previewTitle(idx) {
      if (this.checkTitle()) {
        if (idx === 1) {
          if (!this.formParams.bannerImgUrl) {
            this.$message.error('请先设置完封面图后再预览');
            return;
          }
          this.imgList = [this.formParams.bannerImgUrl];
          this.drawerTitleVisible = true;
        }
        if (idx === 3) {
          if (this.formParams.bannerImgList.length < 3) {
            this.$message.error('请先设置完封面图后再预览');
            return;
          }
          this.imgList = this.formParams.bannerImgList;
          this.drawerTitleVisible = true;
        }
      }
    },
    checkTitle() {
      let title = this.formParams.title;
      if (!title || title.trim() == '') {
        this.$message.error('请输入文章标题');
        return false;
      }
      if (title.length < 5) {
        this.$message.error('文章标题不少于5个字符');
        return false;
      }
      return true;
    },
    checkParams() {
      if (this.checkTitle()) {
        if (!this.editor.txt.html()) {
          this.$message.error('请输入文章内容');
          return false;
        }
        if (this.formParams.radioImg == '1' && !this.formParams.bannerImgUrl) {
          this.$message.error('请上传一张封面');
          return false;
        }
        if (this.formParams.radioImg == '2' && this.formParams.bannerImgList.length !== 3) {
          this.$message.error('请上传三张封面');
          return false;
        }
        return true;
      }
      return false;
    },
    submitPublish(idx, scheduleTime) {
      if (this.checkParams()) {
        const params = {
          title: this.formParams.title,
          content: this.editor.txt.html(),
          postType: 1,
          userId: this.userId,
          videoUrl: '1'
        };
        switch (this.formParams.radioImg) {
          case '1':
            params.coverSize = 1;
            params.coverUrlList = [this.formParams.bannerImgUrl];
            break;
          case '2':
            params.coverSize = 3;
            params.coverUrlList = this.formParams.bannerImgList;
            break;
          case '3':
            params.coverSize = 0;
            params.coverUrlList = [];
            break;
        }
        if (idx == 1) {
          this.btnLoading = true;
          if (this.postId) {
            // 更新帖子
            updatePost(params, { url: `/admin/updatePost/${this.postId}` }).then(res => {
              this.btnLoading = false;
              if (res.success) {
                this.$message({
                  message: '帖子更新成功',
                  type: 'success'
                });
                this.$router.push('/');
              }
            });
          } else {
            createPost(params).then(res => {
              this.btnLoading = false;
              if (res.success) {
                this.$message({
                  message: '帖子发布成功',
                  type: 'success'
                });
                this.$router.push('/');
              }
            });
          }
        }
        if (idx == 2) {
          params.scheduleTime = scheduleTime;
          createSchedulePost(params).then(res => {
            this.selectTimeVisible = false;
            this.timeLoading = false;
            if (res.success) {
              this.$message({
                message: '帖子将在指定时间发布',
                type: 'success'
              });
              this.$router.push('/');
            }
          });
        }
      }
    },
    radioImgChange(lebal) {
      if (lebal == '1' && !this.formParams.bannerImgUrl && this.formParams.bannerImgList.length > 0) {
        this.formParams.bannerImgUrl = this.formParams.bannerImgList[0];
      }
      if (lebal == '2' && this.formParams.bannerImgUrl && this.formParams.bannerImgList.length === 0) {
        this.formParams.bannerImgList.push(this.formParams.bannerImgUrl);
      }
      if (lebal != '2') {
        this.bannerNum = 1;
      }
    },
    moreSelectFlag(idx) {
      switch (idx) {
        case 1:
          return this.moreOneSelectFlag;
        case 2:
          return this.moreTwoSelectFlag;
        case 3:
          return this.moreThreeSelectFlag;
      }
    },
    deleteSelectOneImg() {
      this.oneBannerSelectFlag = false;
      this.formParams.bannerImgUrl = '';
    },
    oneBannerMouseover() {
      this.oneBannerSelectFlag = true;
    },
    oneBannerMouseleave() {
      this.oneBannerSelectFlag = false;
    },
    selectThreeImg(idx) {
      if (this.formParams.bannerImgList.length === 3) {
        this.overstepIdx = idx;
      }
      this.bannerNum = 3;
      this.selectImgVisible = true;
    },
    bannerMouseover(idx) {
      switch (idx) {
        case 1:
          this.moreOneSelectFlag = true;
          break;
        case 2:
          this.moreTwoSelectFlag = true;
          break;
        case 3:
          this.moreThreeSelectFlag = true;
          break;
      }
    },
    bannerMouseleave(idx) {
      switch (idx) {
        case 1:
          this.moreOneSelectFlag = false;
          break;
        case 2:
          this.moreTwoSelectFlag = false;
          break;
        case 3:
          this.moreThreeSelectFlag = false;
          break;
      }
    },
    deleteSelectMoreImg(idx) {
      this.moreOneSelectFlag = false;
      this.moreTwoSelectFlag = false;
      this.moreThreeSelectFlag = false;
      this.formParams.bannerImgList.splice(idx, 1);
    },
    selectRecommendImg(imgUrl) {
      if (this.bannerNum == 1) {
        this.formParams.bannerImgUrl = imgUrl;
      } else {
        if (typeof imgUrl === 'string') {
          if (this.formParams.bannerImgList.length === 3) {
            this.formParams.bannerImgList.splice(this.overstepIdx, 1, imgUrl);
          } else {
            this.formParams.bannerImgList.push(imgUrl);
          }
        } else {
          this.formParams.bannerImgList = imgUrl;
        }
      }
      this.selectImgVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.article {
  position: relative;
  min-height: 100vh;
  background: #fafafa;
  .form-wrap {
    width: 750px;
    background: #fff;
    margin: 0 auto;
    .header {
      position: fixed;
      top: 0;
      left: 0;
      height: 48px;
      text-align: center;
      width: 100%;
      z-index: 1001;
      background: #fafafa;
      border-bottom: 1px solid #eaeaea;
      padding-top: 2px;
      .toolbar {
        width: 750px;
        margin: 0 auto;
        background: #fafafa;
      }
    }
    .textContent {
      width: 750px;
      min-height: 600px;
      background: #fff;
      margin: 78px auto 0;
      padding: 68px 40px 30px;
    }
    .h4 {
      position: absolute;
      top: 0;
      width: 670px;
      height: 60px;
      line-height: 60px;
      border-bottom: 1px solid #f1f1f1;
      margin: 0 40px;
      .outline-title {
        width: 100%;
        height: 40px;
        line-height: 40px;
        font-size: 15px;
        font-weight: 600;
        color: #666;
        outline: none;
        border: 0;
        padding: 0 12px;
      }
    }
    .line-divider {
      border-top: 1px solid #f1f1f1;
      margin: 0 40px;
    }
    .form-container {
      padding: 40px 40px 100px;
      .form-input {
        position: relative;
        width: 100%;
        padding: 6px 10px;
        border-radius: 4px;
        border: solid 1px #d9d9d9;
        margin-top: 20px;
        .my-input {
          border: none;
          height: 22px;
          line-height: 22px;
          outline: none;
          box-shadow: none;
        }
      }
      .article-cover-add {
        position: relative;
        display: inline-block;
        width: 120px;
        height: 85px;
        line-height: 85px;
        margin-right: 12px;
        vertical-align: top;
        text-align: center;
        cursor: pointer;
        border-radius: 4px;
        border: 1px dashed #d8d8d8;
        background-color: #fafafa;
        .template {
          height: 100%;
          .article-cover-img {
            width: 100%;
            height: 100%;
            border-radius: 3px;
            object-fit: cover;
          }
          .article-cover-delete {
            position: absolute;
            right: -8px;
            top: -8px;
          }
        }
      }
      .show-dialog-btn {
        font-size: 14px;
        color: #222;
        vertical-align: bottom;
        cursor: pointer;
      }
      .article-cover-tip {
        margin-top: 12px;
        font-size: 12px;
        color: #999;
      }
    }
  }
  .bottom-fix {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 54px;
    line-height: 54px;
    z-index: 100002;
    background-color: #fff;
    text-align: right;
    border-top: 1px solid #e8e8e8;
    .publish-footer-content {
      height: 100%;
      width: 750px;
      margin: 0 auto;
      .footer-tip {
        font-size: 12px;
        color: #9e9e9e;
        float: left;
        height: 100%;
        vertical-align: middle;
        line-height: 54px;
      }
      .go-back {
        float: left;
        width: 120px;
        text-align: center;
      }
      .footer-btn {
        float: right;
      }
    }
  }
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
